#!/bin/bash

fitfile=$1
galaxylist=$2
if [ $# -ne 2  ]
then
	echo "usage[xfindgalaxy.sh a.fit a.glade ]"
	exit 0
fi

boxpixel=100

mkdir reduc

cp $fitfile $galaxylist reduc
cp -r ~/xsoft/newxgwacmatchsoft/* reduc
cd reduc

Dir_now=`pwd`
tempdir=`echo $Dir_now | awk '{print($1"/")}'`
Dir_now=`echo $tempdir`


cat $galaxylist | awk '{print($8,$9,$1)}' >galaxy.sky
sky2xy $fitfile @galaxy.sky | awk '{print($5,$6,$3,$1,$2)}' | column -t >galaxy.xy
cat galaxy.xy | while read line
do
	echo $line
	xc=`echo $line | awk '{print($1)}'`
	yc=`echo $line | awk '{print($2)}'`
	ID_galaxy=`echo $line | awk '{print($3)}'`
	RAg=`echo $line | awk '{print($4)}'`
	DECg=`echo $line | awk '{print($5)}'`
	
	prefix=`echo $fitfile | sed 's/\.fit//g'`	
	imsubname=`echo $ID_galaxy $prefix | awk '{print($1"_"$2".fit")}'`
	ccdimgjpg=`echo $imsubname | sed 's/\.fit/.jpg/g'`
	CCDsize=`gethead $fitfile "NAXIS1" | awk '{print($1)}'`
    	CCDsize_Big=`echo $CCDsize | awk '{print($1-1)}'`

        #echo $FILEforsub $imsubname $xim $yim 
    	xmin=`echo  $xim | awk '{printf("%.0f", $1-tsize)}' tsize=$boxpixel`
    	xmax=`echo  $xim | awk '{printf("%.0f", $1+tsize)}' tsize=$boxpixel`
    	ymin=`echo  $yim | awk '{printf("%.0f", $1-tsize)}' tsize=$boxpixel`
    	ymax=`echo  $yim | awk '{printf("%.0f", $1+tsize)}' tsize=$boxpixel`
    	xshift=1
    	yshift=1

    	if [ $(echo "$xmin < 0"|bc) = 1 ]
    	then
        xshift=`echo $xmin | awk '{print($1-0)}'`
        xmin=1
    	fi
    	if [ $(echo "$xmax >= $CCDsize" |bc) = 1 ]
    	then
        	xmax=$CCDsize_Big
    	fi

    	if [ $(echo "$ymin < 0" |bc) = 1 ]
    	then
        	yshift=`echo $ymin | awk '{print($1-0)}'`
        	ymin=1
    	fi

    	if [ $(echo "$ymax >= $CCDsize" |bc) = 1 ]
    	then
        	ymax=$CCDsize_Big
    	fi

	/home/w60ccd/software/anaconda3/bin/python get_sub_fits_xy.py $Dir_now  $fitfile $Dir_now $imsubname $xmin $xmax $ymin $ymax
	sethead -kr X RA_G=$RAg DEC_G=$DECg   $imsubname
	python fits_cut_to_png.py $imsubname $ccdimgjpg 50 50 50 ""
	wait
	mv $ccdimgjpg $imsubname ../
done
rm -rf galaxy.sky galaxy.xy
cd ../
rm -rf reduc
echo "========finished========="

